package fact.test;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.CustomScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

import com.icesoft.faces.component.tree.IceUserObject;

import fact.view.DTO.NodeDTO;
import fact.view.model.FactReportModelBean;



@ManagedBean(name= "tree")
//@RequestScoped
@CustomScoped(value = "#{window}")
public class TreeBean   implements Serializable {
    
    public static final String BEAN_NAME = "tree";
    public static final String IMAGE_PATH = "/xmlhttp/css/rime/css-images/";
    public static String imgUrl="/FACTENTRY/javax.faces.resource/navIcon/";
    
    
    //public static final String IMAGE_ICON = "tree_document.gif";
    //public static final String IMAGE_ICON ="/FACTENTRY/javax.faces.resource/pink.png.jsf?ln=images";
    //public static final String IMAGE_CLOSED = "tree_folder_closed.gif";
    //public static final String IMAGE_OPEN = "tree_folder_open.gif";
    
    public static final String RED_IMAGE_OPEN = imgUrl+"redOpen.png"+".jsf?ln=images";
    public static final String RED_IMAGE_CLOSE = imgUrl+"redClose.png"+".jsf?ln=images";
    public static final String GREEN_IMAGE_OPEN = imgUrl+"greenOpen.png"+".jsf?ln=images";
    public static final String GREEN_IMAGE_CLOSE = imgUrl+"greenClose.png"+".jsf?ln=images";
    public static final String YELLOW_IMAGE_OPEN = imgUrl+"yellowOpen.png"+".jsf?ln=images";
    public static final String YELLOW_IMAGE_CLOSE = imgUrl+"yellowClose.png"+".jsf?ln=images";
    
    public static final String RED_IMAGE_LEAF = imgUrl+"leafRed.png"+".jsf?ln=images";
    public static final String GREEN_IMAGE_LEAF = imgUrl+"leafGreen.png"+".jsf?ln=images";
    public static final String YELLOW_IMAGE_LEAF = imgUrl+"leafYellow.png"+".jsf?ln=images";
    

    private static final Random randomizer = new Random(System.nanoTime());
    private DefaultTreeModel model;
    
    @ManagedProperty(value="#{testModelBean}")
    private TestDAO testModelBean;
    
    @PostConstruct
    public void init() 
    {

        model = generateRandomTree();
    }


    public  DefaultTreeModel generateRandomTree() {
        return generateRandomTree(2, 3, 1, 5);
    }
    public void refreshTree(ActionEvent event) {
        model = generateRandomTree();
    }

    public  DefaultTreeModel generateRandomTree(int minFolder, int randFolder,
                              int minLeaf, int randLeaf) 
    {
    	ArrayList<NodeDTO> nodeList=new ArrayList<NodeDTO>();
    	try{
    		nodeList=testModelBean.getNodeList();
    	}
    	catch(Exception ex)
    	{
    		ex.printStackTrace();
    	}
    	HashMap parentHash = new HashMap();
    	HashMap labelHash = new HashMap();
    	HashMap nodeHash=new HashMap();
    	// Put elements to the map
  
    	for(int i=0;i<nodeList.size();i++)
    	{
    		nodeHash.put(((NodeDTO)nodeList.get(i)).getNodeId(), ((NodeDTO)nodeList.get(i)).getParentId());
    		labelHash.put(((NodeDTO)nodeList.get(i)).getNodeId(), ((NodeDTO)nodeList.get(i)).getNodeName());
    	}
    	
    	
    		
        // Setup the root node
        DefaultMutableTreeNode rootNode = addNode(null, "System",0,"", false);
        
        DefaultTreeModel toReturn = new DefaultTreeModel(rootNode);
        DefaultMutableTreeNode folderNode = null;
        
        for(int i=0;i<nodeList.size();i++)
        {
        	if(((NodeDTO)nodeList.get(i)).getParentId()==0)
        	{
        		folderNode=addNode(rootNode, ((NodeDTO)nodeList.get(i)).getNodeName(), ((NodeDTO)nodeList.get(i)).getNodeId(),"",false);
        		nodeHash.put(((NodeDTO)nodeList.get(i)).getNodeId(), folderNode);
        		
        	}
        	else
        	{
        		
        		if(((NodeDTO)nodeList.get(i)).getIsLeaf()==1)
        		{
        			addNode((DefaultMutableTreeNode)nodeHash.get(((NodeDTO)nodeList.get(i)).getParentId()), ((NodeDTO)nodeList.get(i)).getNodeName(),((NodeDTO)nodeList.get(i)).getNodeId(),((NodeDTO)nodeList.get(i)).getStatus(), true);
        		}
        		else
        		{
        			folderNode=addNode((DefaultMutableTreeNode)nodeHash.get(((NodeDTO)nodeList.get(i)).getParentId()), ((NodeDTO)nodeList.get(i)).getNodeName(),((NodeDTO)nodeList.get(i)).getNodeId(),((NodeDTO)nodeList.get(i)).getStatus(), false);
        		}
        		nodeHash.put(((NodeDTO)nodeList.get(i)).getNodeId(), folderNode);
        	}
        }
        
        /*
        
        // Setup each folder and child
        //DefaultMutableTreeNode folderNode = null;
        int numFolders = minFolder+randomizer.nextInt(randFolder);
        int numLeaf = -1;
        
        
        for (int i = 0; i < numFolders; i++) {
            folderNode = addNode(rootNode, "Folder " + (i+1), false);

            numLeaf = minLeaf+randomizer.nextInt(randLeaf);

            for (int j = 0; j < numLeaf; j++) {
                addNode(folderNode, "Item " + (i+1) + "-" + j, true);
            }
        }
        */
        
        
        return toReturn;
    }

    public static DefaultMutableTreeNode addNodeToRoot(DefaultTreeModel model, String text,int nodeId,String status, boolean isLeaf) {
        return addNode((DefaultMutableTreeNode)model.getRoot(), text,nodeId,status, isLeaf);
    }

    public static DefaultMutableTreeNode addNode(DefaultMutableTreeNode parent, String text,int nodeId,String status,boolean isLeaf) {
        DefaultMutableTreeNode node = new DefaultMutableTreeNode();
        IceUserObject userObject = new IceUserObject(node);
        node.setUserObject(userObject);

        // Customize our new node
        userObject.setLeaf(isLeaf);
        userObject.setText(text);
        userObject.setTooltip(text);
        node.setAllowsChildren(!isLeaf);
        
        userObject.setAction(String.valueOf(nodeId));
        // Set the image icons
        //userObject.setLeafIcon(makeIcon(IMAGE_ICON));
        //userObject.setBranchContractedIcon(makeIcon(IMAGE_CLOSED));
        //userObject.setBranchExpandedIcon(makeIcon(IMAGE_OPEN));        
        if(isLeaf==true)
        {
        	if(status==null || status.equalsIgnoreCase("N"))
            	userObject.setLeafIcon(RED_IMAGE_LEAF);
        	else if(status.equalsIgnoreCase("S"))
        		userObject.setLeafIcon(YELLOW_IMAGE_LEAF);
        	else if(status.equalsIgnoreCase("A"))
            	userObject.setLeafIcon(GREEN_IMAGE_LEAF);
            	
        }
        else
        {
            userObject.setBranchContractedIcon(RED_IMAGE_CLOSE);
            userObject.setBranchExpandedIcon(RED_IMAGE_OPEN);        

        }

    // Expand if we're not a leaf
    if (!isLeaf) {
        userObject.setExpanded(true);
    }

    // Add the completed node to the parent
    if (parent != null) {
        parent.add(node);
    }

    return node;
    }

    public static String makeIcon(String image) {
        return IMAGE_PATH + image;
    }

    public DefaultTreeModel getModel() { return model; }
    public void setModel(DefaultTreeModel model) { this.model = model; }

	public TestDAO getTestModelBean() {
		return testModelBean;
	}

	public void setTestModelBean(TestDAO testModelBean) {
		this.testModelBean = testModelBean;
	}
    
    
}